package net.hanjava.roas;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Generate *.properties for a resource sheet.
 * @author accent
 */
public class PropertiesGenerator {
    private ResourceSheet sheet;

    private File outputDir;

    private int defaultLocaleColIndex = 1;

    public PropertiesGenerator(ResourceSheet sheet, File outputDir) {
        this.sheet = sheet;
        this.outputDir = outputDir;
    }

    public void setDefaultLocaleColumn(int index) {
        this.defaultLocaleColIndex = index;
    }

    public void generate() {
        int rc = sheet.getRowCount();
        if(rc<0) return;
        String[] locales = SheetUtil.getLocales(sheet);
        for(int i = 0; i < locales.length; i++) {
            // 1 based (column 0 is for keys)
            try {
                generateForLocale(i + 1);
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void generateForLocale(int colIndex) throws IOException {
        if(!outputDir.exists()) {
            outputDir.mkdirs();
        }

        String baseName = sheet.getName();
        String suffix = '_' + sheet.get(0, colIndex);
        if(colIndex == defaultLocaleColIndex)
            suffix = "";
        String fname = baseName + suffix + ".properties";
        File f = new File(outputDir, fname);
        Properties prop = new Properties();
        FileOutputStream fos = new FileOutputStream(f);
        int rc = sheet.getRowCount();
        for(int r = 1; r < rc; r++) {
            String key = sheet.get(r, 0);
            String value = sheet.get(r, colIndex);
            prop.setProperty(key, value);
        }
        prop.store(fos, "Generated by ROAS(http://roas.googlecode.com)");
        fos.close();
    }
}